@echo off
setlocal enabledelayedexpansion

REM 设置 UV4.exe 的路径
set UV=D:\SoftWare\MDK\Core\UV4\UV4.exe

REM 检查 UV4.exe 是否存在
if not exist "!UV!" (
    echo UV4.exe not found at path: !UV!
    echo Please check the path to UV4.exe.
    goto end
)

REM 查找工程文件并把UV_PRO_PATH设置成工程路径
set n=0
set UV_PRO_PATH=
for /f "delims=" %%i in ('dir /s/b/a-d ^| findstr ".uvprojx .uvproj"') do (
    if !n! equ 0 (
        set UV_PRO_PATH=%%i
        set /a n=!n!+1
    ) else (
        set /a n=!n!+1
    )
)
@REM echo Found projects: !n!

if !n! gtr 1 (
    echo Not the only Project, Please check project number
    goto end
)
if !n! equ 0 (
    echo No ProjectName
    goto end
)

REM 开始编译或烧录
if "!UV_PRO_PATH!" == "" goto NOP
if "%1" == "-b" (
    REM 编译
    echo Init building ... 
    !UV! -j0 -sg -b "!UV_PRO_PATH!" -o "%cd%\build_log.txt"
    type "%cd%\build_log.txt"
) else if "%1" == "-f" (
    REM 烧录
    echo Init flashing ...  
    !UV! -j0 -sg -f "!UV_PRO_PATH!" -o "%cd%\build_log.txt"
    type "%cd%\build_log.txt"
) else if "%1" == "-r" (
    REM 全局编译
    echo Init building all ...  
    !UV! -j0 -sg -r "!UV_PRO_PATH!" -o "%cd%\build_log.txt"
    type "%cd%\build_log.txt"
) else if "%1" == "-c" (
    REM 清除工程
    echo make clean ...  
    del /s /q *.bin
    !UV! -j0 -sg -c "!UV_PRO_PATH!" -o "%cd%\build_log.txt"
    type "%cd%\build_log.txt"
) else (
    REM 仅编译
    echo Init building ... 
    !UV! -j0 -sg -b "!UV_PRO_PATH!" -o "%cd%\build_log.txt"
    type "%cd%\build_log.txt"
)
echo Done.
goto end

:NOP
echo No ProjectName
goto end

:NO_ONLY
echo Not the only Project, Please check project number
goto end

:end
REM 删除日志文件
if exist "%cd%\build_log.txt" del "%cd%\build_log.txt"
REM 打开下面这个注释可能导致控制台窗口在编译完成后关闭
::exit